<template>
  <div class="kafka-panel panel">
    <h1>Kafka Broker 实例列表</h1>
    <el-table :data="instances" border style="width: 100%" @row-click="handleRowClick">
      <el-table-column prop="brokerId" label="Broker ID" width="100"></el-table-column>
      <el-table-column prop="host" label="主机地址"></el-table-column>
      <el-table-column prop="port" label="端口" width="100"></el-table-column>
      <el-table-column prop="version" label="版本号" width="120"></el-table-column>
    </el-table>

    <!-- 展开详情 -->
    <el-collapse v-model="activeCollapse">
      <el-collapse-item title="详细信息" name="details">
        <div v-if="selectedInstance">
          <p><strong>Broker ID:</strong> {{ selectedInstance.brokerId }}</p>
          <p><strong>Host:</strong> {{ selectedInstance.host }}</p>
          <p><strong>Port:</strong> {{ selectedInstance.port }}</p>
          <p><strong>Version:</strong> {{ selectedInstance.version }}</p>

          <div v-if="metricsLoading">加载中...</div>
          <div v-else>
            <p>分区数：{{ metrics.partitions }}</p>
            <p>副本数：{{ metrics.replicas }}</p>
            <p>生产消息速率：{{ metrics.producerRate }} 条/秒</p>
            <p>消费消息速率：{{ metrics.consumerRate }} 条/秒</p>
          </div>
        </div>
        <div v-else>请选择一个实例查看详细信息。</div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const instances = ref([]);
const selectedInstance = ref(null);
const activeCollapse = ref('');
const metrics = ref({});
const metricsLoading = ref(false);

onMounted(async () => {
  try {
    const res = await axios.get('/api/kafka/brokers');
    instances.value = res.data;
  } catch (err) {
    console.error('获取 Kafka 实例失败', err);
  }
});

function handleRowClick(row) {
  selectedInstance.value = row;
  activeCollapse.value = 'details';
  loadMetrics(row);
}

async function loadMetrics(instance) {
  metricsLoading.value = true;
  try {
    const res = await axios.get(`/api/kafka/metrics/${instance.brokerId}`);
    metrics.value = res.data;
  } catch (err) {
    console.error('获取 Kafka 实例监控数据失败', err);
  } finally {
    metricsLoading.value = false;
  }
}
</script>
